<template>
	<view class="center">
		<uni-sign-in ref="signIn"></uni-sign-in>
		<view class="userInfo" @click.capture="toUserInfo">
			
			<view class='logo-image'>
				<cloud-image width="60rpx" height="160rpx" v-if="userInfo.avatar_file&&userInfo.avatar_file.url"
					:src="userInfo.avatar_file.url"></cloud-image>
				<image v-else class="logo-img" src="@/static/uni-center/defaultAvatarUrl.png"></image>
			</view>
			<view class="logo-title">
				<text class="uer-name" v-if="hasLogin">{{userInfo.empname||userInfo.userName||userInfo.mobile}}</text>
				<text class="uer-name" v-else>{{$t('mine.notLogged')}}</text>
			</view>
			
		</view>
		<view v-if="hasLogin">

			<view class="innner-line-other">
				<view class='other-image'>
					<image class="other-img" src="@/static/uni-center/department.png"></image>
				</view>
				<view class="other-data">
					部门：{{userInfo.deptname}}
				</view>
				
			</view>
			<view class="innner-line-other">
				<view class='other-image'>
					<image class="other-img" src="@/static/uni-center/phone.png"></image>
				</view>
				<view class="other-data">
					电话：{{userInfo.mobile}}
				</view>
			</view>
			<view class="innner-line-other">
				<view class='other-image'>
					<image class="other-img" src="@/static/uni-center/about.png"></image>
				</view>
				<view class="other-data">
					关于
				</view>
			</view>
		</view>
		<view v-if="!hasLogin" class="bottom-back" >
			<button :disabled="!isAgree" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber"
				class="loginbutton">{{$t('settings.login')}}</button>
			<view class="privary">
				<checkbox-group class="privary-check" @change="setAgree">
					<label class="checkbox-box">
						<checkbox :checked="isAgree" style="transform: scale(0.5);margin-right: -6px;" />
						<text class="text">已阅读并同意</text>
					</label>
				</checkbox-group>
				<view class="content">
					<view class="agree-item" v-for="(agreement,index) in agreements" :key="index">
						<text class="agreement text" @click="navigateTo(agreement)">{{agreement.title}}</text>
						<text class="text and" v-if="hasAnd(agreements,index)" space="nbsp"> 和 </text>
					</view>
				</view>
			</view>
		</view>

		<!-- 退出/登录 按钮 -->
		<view v-if="hasLogin" class="bottom-back">
			<button class="logoutbutton" @click="clickLogout">{{$t('settings.logOut')}}</button>
		</view>
	</view>
</template>

<script>
	import {
		mapGetters,
		mapMutations
	} from 'vuex';
	import mixin from '@/pages/ucenter/login-page/common/login-page.mixin.js';
	import WXBizDataCrypt from "@/common/WXBizDataCrypt.js";
	export default {
		mixins: [mixin],
		data() {
			return {
				gridlist: [{
						image: "https://www.dtxtkj.com/app/uni-center/defaultAvatarUrl.png",
					},
					{
						text: "",
					}
				],
				listStyles: {
					"height": "150rpx", // 边框高度
					"width": "150rpx", // 边框宽度
					"border": { // 如果为 Boolean 值，可以控制边框显示与否
						"color": "#eee", // 边框颜色
						"width": "1px", // 边框宽度
						"style": "solid", // 边框样式
						"radius": "100%" // 边框圆角，支持百分比
					}
				},
				isChecked:false,
				openid:"",
				isAgree: false,
				needAgreements:true,
				needPopupAgreements:false
			}
		},
		onLoad() {
			let hasSubscribed = uni.getStorageSync('hasSubscribe');
			if(hasSubscribed === "hasSubscribed"){
				this.isChecked=true;
			}
			let logout = getApp().globalData.logout;
			//非法用户注销登录
			if(logout === 1){
				this.userLogout();
				getApp().globalData.logout = 0;
			}
			wx.login({
				success: (res) => {
					console.log("get user info begion");
					if (res.code) { //微信登录成功 已拿到code
						this.jsCode = res.code //保存获取到的code  
						let params = {
							jsCode: res.code,
							grantType: 'authorization_code'
						}
						this.$api.reqAppID(params).then(result => {
							this.openid = result.openid //unionid 开放平台唯一标识
							this.session_key = result.session_key //session_key  会话密钥  
							this.unionid = result.unionid
							
						}).catch(res => {
							console.log("get reqAppid error");
							console.log(res);
						})
					} else {
						console.log('登录失败！' + res.errMsg)
					}
					console.log("get user info end");
				}
			})
		},
		computed: {
			...mapGetters({
				userInfo: 'user/info',
				hasLogin: 'user/hasLogin'
			}),
			appConfig() {
				return getApp().globalData.config
			},
			agreements() {
				return [
					{
						url:'/pages/ucenter/user-agree/user-agree',
						title:"用户服务协议"
					},
					{
						url:'/pages/ucenter/privary/privary',
						title:"隐私政策条款"
					}
				]
			}
		},
		props: {
			scope: {
				type: String,
				default(){
					return 'register'
				}
			},
		},
		methods: {
			...mapMutations({
				setUserInfo: 'user/login'
			}),
			toSettings() {
				uni.navigateTo({
					url: "/pages/ucenter/settings/settings"
				})
			},
			/**
			 * 个人中心项目列表点击事件
			 */
			ucenterListClick(item) {
				if (!item.to && item.event) {
					this[item.event]();
				}
			},
			async checkVersion() {
				let res = await callCheckVersion()
				console.log(res);
				if (res.result.code > 0) {
					checkUpdate()
				} else {
					uni.showToast({
						title: res.result.message,
						icon: 'none'
					});
				}
			},
			toUserInfo() {
				uni.navigateTo({
					url: '/pages/ucenter/userinfo/userinfo'
				})
			},
			getPhoneNumber(e) {
				if (e.detail.errMsg == "getPhoneNumber:fail user deny") { 
					//用户决绝授权  
					uni.showModal({
						title: this.$t('common').error,
						content: "授权失败",
						showCancel: false,
						confirmText: this.$t('common').gotIt
					});

				} else {
					if (!this.session_key) {
						uni.showModal({
							title: this.$t('common').error,
							content: "获取授权失败",
							showCancel: false,
							confirmText: this.$t('common').gotIt
						});
					}
					//允许授权  
					let pc = new WXBizDataCrypt('wx65fd1de7f30a9b00', this.session_key); //wxXXXXXXX为你的小程序APPID  
					console.log(e.detail.encryptedData);
					console.log(e.detail.iv);
					let data = pc.decryptData(e.detail.encryptedData, e.detail.iv);
					console.log(data); //data就是最终解密的用户信息
					// 访问后台接口校验权限
					this.getUserAuth(data.phoneNumber);
				}

			},
			getUserAuth(phoneNumber) {
				let params = {
					// mobile: "18091274855", // 创建报价单  李字刚
					// mobile: "13720718860", // 创建报价单  乔小华
					// mobile: "15667724444", // 审批报价单1
					// mobile: "13891272288", // 审批报价单2
					// mobile: "13772900023", // 审批报价单3
					// mobile: "13992255436", // 任叔
					// mobile: "18192963723", // 孙老师
				    // mobile: phoneNumber,
					openid: this.openid,
					unionid: this.unionid,
				}
				this.$api.login(params).then(result => {
					if(!result){
						uni.showModal({
							title: this.$t('common').error,
							content: "校验失败",
							showCancel: false,
							confirmText: this.$t('common').gotIt
						});
						return;
					}
					
					if(result.code === 211){
						uni.showModal({
							title: this.$t('common').error,
							content: "无权限用户",
							showCancel: false,
							confirmText: this.$t('common').gotIt
						});
						return;
					}
					console.log(result);
					console.log(wx.getUserInfo());
					let loginResult = new Object;
					loginResult.userInfo = result;
					if(result.body){
						let hasAuthBilltype = [];
						for(let billtype in result.body){
							if(result.body[billtype].enable ===1){
								hasAuthBilltype.push(parseInt(result.body[billtype].billtype));
							}
						}
						loginResult.userInfo.hasAuthBilltype = hasAuthBilltype;
					}
					
					this.loginSuccess(loginResult);
					//this.requestSubscribeMessage();
					
				}).catch(res => {
				　　uni.showModal({
						title: this.$t('common').error,
						content: "校验失败",
						showCancel: false,
						confirmText: this.$t('common').gotIt
					});
					return;
				})
				
			},
			
		requestSubscribeMessage(res){
			this.isChecked=!this.isChecked;
			if(this.isChecked==false){
				uni.removeStorageSync('hasSubscribe','');
				return;
			}
			//let templateId = 'drmmkNYGmmpCC5HF2M0RQ6ze_5EyECk-roQJE9Lp5XM';
			uni.requestSubscribeMessage({
			        tmplIds: ['drmmkNYGmmpCC5HF2M0RQ6ze_5EyECk-roQJE9Lp5XM','drmmkNYGmmpCC5HF2M0RQ7H6JxLOVh9VcBTDZ_HYLiU'],
			        success: (res) => {
						uni.setStorageSync('hasSubscribe','hasSubscribed');
			            console.log("订阅成功！")
			        },
					fail:()=>{
						uni.setStorageSync('hasSubscribe','');
						 console.log("订阅失败！")
					}
			    })
			},	
			clickLogout() {
				console.log("logout begin")
				this.userLogout();
				this.isAgree = false;
			},
			async share() {},
			popupConfirm(){
				this.isAgree = true;
				retryFun()
				// this.$emit('popupConfirm')
			},
			popup(Fun){
				this.needPopupAgreements = true
				// this.needAgreements = true
				this.$nextTick(()=>{
					if(Fun){
						retryFun = Fun
					}
					this.$refs.popupAgreement.open()
				})
			},
			navigateTo({
				url,
				title
			}) {
				uni.navigateTo({
					url: url,
					success: res => {},
					fail: () => {},
					complete: () => {}
				});
			},
			hasAnd(agreements, index) {
				return agreements.length - 1 > index
			},
			setAgree(e) {
				this.isAgree = !this.isAgree
				this.$emit('setAgree', this.isAgree)
			}
		}
	}
</script>

<style lang="scss" scoped>
	/* #ifndef APP-NVUE */
	view {
		display: flex;
		box-sizing: border-box;
		flex-direction: column;
	}

	page {
		background-color: #f8f8f8;
	}

	.logo-image {
		width: 100rpx;
		height: 100rpx;
		display: inline-block;
		flex: 1;
		border-radius: 150rpx;
		vertical-align:middle;
	}
	
	.other-image {
		width: 80rpx;
		height: 80rpx;
		display: inline-block;
		flex: 1;
		border-radius: 150rpx;
		vertical-align:middle;
	}

	.logo-title {
		width: 150rpx;
		height: 150rpx;
		display: inline-block;
		flex: 3;
		justify-content: space-between;
		flex-direction: row;
		text-align: left;
		font-size: 14px;
		color: #000000;
	}
	
	.logo-data {
		width: 250rpx;
		height: 50rpx;
		display: inline-block;
		flex: 3;
		justify-content: space-between;
		flex-direction: row;
		text-align: left;
		font-size: 20px;
		color: #000000;
		margin: 0 25px 0;
	}
	
	.other-data {
		height: 50rpx;
		display: inline-block;
		flex: 3;
		justify-content: space-between;
		flex-direction: row;
		text-align: left;
		font-size: 15px;
		color: #000000;
		margin: 0 25px 0;
	}
	.innner-line ,.innner-title{
		padding: 0 20px 0;
		line-height: 60px;
		border-bottom: 1px solid #ddd;
	}
	
	.innner-title{
		font-size: 20px;
		font-weight: 600;
	}

	.innner-line2 {
		padding: 0 20px 0;
		line-height: 60px;
		display: flow-root;
	}
	.innner-line-other{
		padding: 0 20px 0;
		line-height: 60px;
		border-bottom: 1px solid #ddd;
		display: flow-root;
	}

	.logo-img {
		width: 120rpx;
		height: 120rpx;
		border-radius: 150rpx;
	}
	
	.other-img {
		width: 80rpx;
		height: 80rpx;
		border-radius: 100rpx;
	}

	// 默认样式
	.loginbutton {
		width: 90%;
		margin-bottom: 10rpx;
		border: 1px solid #DCDFE6;
		border-radius: 25px;
		color: #fff;
		font: 16px 'microsoft yahei';
		height: 40px;
		line-height: 40px;
		background-color: #2979ff;
		text-align: center;
	}
	
	// 默认样式
	.logoutbutton {
		width: 50%;
		margin-bottom: 10rpx;
		border: 1px solid #DCDFE6;
		border-radius: 25px;
		color: #000;
		font: 16px 'microsoft yahei';
		height: 40px;
		line-height: 40px;
		background-color: #fff;
		text-align: center;
	}
	

	// 边框样式
	button::after {
		border: 0;
	}

	// 禁用时样式
	button[disabled] {
		background-color: #fff;
		color: #666;
	}

	// 点击时样式
	.button-hover {
		color: rgba(0, 0, 0, 0.6);
		background-color: #fff;
	}

	/* #endif*/

	.center {
		flex: 1;
		flex-direction: column;
		background-color: #f8f8f8;
	}

	.userInfo {
		width: 750rpx;
		padding: 20rpx;
		padding-top: 50px;
		background-image: url("https://www.bx-bustrade.cn/bxapp/images/background/back.png");
		background-repeat: no-repeat;
		background-size:cover;
		flex-direction: row;
		border-bottom: 10px solid #ddd;
	}



	.uer-name {
		height: 100rpx;
		line-height: 100rpx;
		font-size: 38rpx;
		color: #fff;
	}

	.center-list {
		margin-bottom: 30rpx;
		background-color: #f9f9f9;
	}

	.center-list-cell {
		width: 750rpx;
		background-color: #007AFF;
		height: 40rpx;
	}

	.grid {
		background-color: #FFFFFF;
		margin-bottom: 6px;
	}

	.uni-grid .text {
		font-size: 30rpx;
		height: 25px;
		line-height: 25px;
		color: #817f82;
	}

	.uni-grid .item ::v-deep .uni-grid-item__box {
		justify-content: center;
		align-items: center;
	}


	/*修改边线粗细示例*/
	/* #ifndef APP-NVUE */
	.center-list ::v-deep .uni-list--border:after {
		-webkit-transform: scaleY(0.2);
		transform: scaleY(0.2);
		margin-left: 80rpx;
	}

	.center-list ::v-deep .uni-list--border-top,
	.center-list ::v-deep .uni-list--border-bottom {
		display: none;
	}

	/* #endif */
	.item-footer {
		flex-direction: row;
		align-items: center;
	}

	.item-footer-text {
		color: #999;
		font-size: 24rpx;
		padding-right: 10rpx;
	}

	.item-footer-badge {
		width: 20rpx;
		height: 20rpx;
		/* #ifndef APP-NVUE */
		border-radius: 50%;
		/* #endif */
		/* #ifdef APP-NVUE */
		border-radius: 10rpx;
		/* #endif */
		background-color: #DD524D;
	}


	.bottom-back {
		margin-top: 10px;
		width: 750rpx;
		height: 150px;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: column;
		justify-content: center;
		align-items: center;
		/* #ifndef APP-NVUE */
		border: none;
		/* #endif */
		border-width: 0;
		border-radius: 0;
		background-color: #FFFFFF;
	}

	.bottom-back-text {
		font-size: 33rpx;
	}

	.item {
		width: 750rpx;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
	}

	.chooseAvatar {
		border: dotted 1px #ddd;
		border-radius: 10px;
		text-align: center;
		width: 50px;
		height: 50px;
		line-height: 50px;
	}
	
	.privary{
		display: flex;
		box-sizing: border-box;
		flex-direction: column;
		flex-direction: row;
		align-items: center;
		font-size: 13px;
		color: #8a8f8b;
		
		view{
			display: flex;
			box-sizing: border-box;
		}
	}
	
	.checkbox-box ,.uni-label-pointer{
		align-items: center;
		display: flex;
		flex-direction: row;
	}
	
	.agree-item {
		flex-direction: row;
	}
	.text{
		line-height: 26px;
	}
	.agreement {
		color: #04498c;
		cursor: pointer;
	}
	
	.checkbox-box ::v-deep .uni-checkbox-input{
		border-radius: 100%;
	}
	
	.checkbox-box ::v-deep .uni-checkbox-input.uni-checkbox-input-checked{
		border-color: $uni-color-primary;
		color: #FFFFFF !important;
		background-color: $uni-color-primary;
	}
	
	.content{
		flex-wrap: wrap;
		flex-direction: row;
	}
	
	.root ::v-deep .uni-popup__error{
		color: #333333;
	}
	
	.privary-check{
		width:auto;
	}
	
</style>
